package com.android.pagemarket.ui.activity.price;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;

import com.android.pagemarket.MyApplication;
import com.android.pagemarket.R;
import com.android.pagemarket.business.logic.InitManager;
import com.android.pagemarket.business.model.PaperType;
import com.android.pagemarket.business.model.QuotType;
import com.android.pagemarket.business.model.Region;
import com.android.pagemarket.io.protocol.in.HttpAction;
import com.android.pagemarket.io.protocol.in.HttpAction.ActionListener;
import com.android.pagemarket.io.protocol.in.QuotAction;
import com.android.pagemarket.io.protocol.in.QuotExcelAction;
import com.android.pagemarket.io.protocol.in.QuotMarkAction;
import com.android.pagemarket.io.protocol.out.ExcelHtml;
import com.android.pagemarket.io.protocol.out.QuotInfo;
import com.android.pagemarket.io.protocol.out.QuotMark;
import com.android.pagemarket.ui.activity.base.LoadableActivity;
import com.android.pagemarket.ui.adapter.AreaArrayAdapter;
import com.android.pagemarket.ui.adapter.PaperTableAdapter;
import com.android.pagemarket.ui.adapter.QuotTypeListAdapter;
import com.android.pagemarket.ui.widget.CallPopWindow;
import com.android.pagemarket.ui.widget.DirectPopWindow;
import com.android.pagemarket.ui.widget.MarkPopWindow;
import com.android.pagemarket.ui.widget.TitleBar;
import com.android.pagemarket.ui.widget.TitleBar.OnTitleClickListener;
import com.android.pagemarket.util.NotifyListener;

/*********************************************************
 * @author : zhaohua
 * @version : 2012-11-1
 * @see : 最新报价视图
 * @Copyright : copyrights reserved by personal 2007-2011
 **********************************************************/
public class NewPriceActivity extends LoadableActivity 
implements OnClickListener,OnItemClickListener
{  
   
    private View bottom;
    private Button btn_see_singl;
    private Button btn_see_double;
    private MarkPopWindow  markPopwin;
    private CallPopWindow  callPopwin;
    private Spinner        spinner_area;
    private Spinner        spinner_type;
    private ListView       listView;
    private QuotTypeListAdapter quotTypeAdapter;
    private PaperTableAdapter paperTablerAdapter;
    private AreaArrayAdapter<Region> areaAdapter;
    private AreaArrayAdapter<QuotType> typeAdapter;
    private boolean isSinglMode = true;
    private PaperType curPaperType;
    private String markContnet;
    
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);        
        setContentView(R.layout.activity_newprice);
        initViews();
        load();
    }
    
    @Override
    protected void setupTitleBar(TitleBar titleBar)
    {
        titleBar.setTitle(R.string.title_newprice);
        titleBar.setRigthText(R.string.tx_mark);
        titleBar.setOnTitleClickListener(new OnTitleClickListener()
        {
            @Override
            public void onRightClick()
            {
                // 查看备注
                showMarkPopWin();
            }
        }, false, true);
    }
     
    @Override
    protected void setupBottomBar(LinearLayout bottomBar)
    {
        bottom = inflate(R.layout.view_bottom_price);
        bottomBar.addView(bottom, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
        spinner_area = getViewById(R.id.spinner_area);
        spinner_type = getViewById(R.id.spinner_type);
        
        areaAdapter = new AreaArrayAdapter<Region>(this);
        spinner_area.setAdapter(areaAdapter);
        typeAdapter = new AreaArrayAdapter<QuotType>(this);
        spinner_type.setAdapter(typeAdapter);
        
        spinner_area.setOnItemSelectedListener(new OnItemSelectedListener()
        {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                    int position, long id)
            {
                    Region   region =  (Region)spinner_area.getSelectedItem();
                    QuotType type   =  (QuotType)spinner_type.getSelectedItem();
                    load(region.rid, type.qid);
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent)
            {
                
            }
        });
    }

    @Override
    protected void onResume()
    {
        super.onResume();       
    }
    
    @SuppressWarnings("unchecked")
    private void initOk()
    {
        bottom.setVisibility(View.VISIBLE);
        if(InitManager.getInstance().isLogin())
        {
            Region region = new Region();
            region.rid = "001";
            region.regionName = InitManager.getInstance().mLoginCompany.regionName;
            areaAdapter.add(region);
            QuotType type = new QuotType();
            type.qid = 1;
            type.quotName = InitManager.getInstance().mLoginCompany.offerType;
            typeAdapter.add(type);
            spinner_area.setSelection(0);
            spinner_type.setSelection(0);
            // 登录的用户不能选择选项
            spinner_area.setEnabled(false);
            spinner_type.setEnabled(false);
        }else
        {
            if(!InitManager.getInstance().initRegionAdapter(areaAdapter))
            {
                spinner_area.setVisibility(View.GONE);
            }
            if(!InitManager.getInstance().initQuotTypeAdapter(typeAdapter))
            {
                spinner_type.setVisibility(View.GONE);
            }
        }
        /**
        if(areaAdapter.getCount() > 0 && typeAdapter.getCount() > 0)
        {
            Region   region =  (Region)areaAdapter.getItem(0);
            QuotType type   =  (QuotType)typeAdapter.getItem(0);
            load(region.rid, type.qid);
        }*/
    }
    
    @Override
    public void refreshView()
    {
        Region   region =  (Region)spinner_area.getSelectedItem();
        QuotType type   =  (QuotType)spinner_type.getSelectedItem();
        if(region != null && type != null)
        {
            load(region.rid, type.qid);
        }
    }
    
    @Override
    public void onClick(View v)
    {
        switch(v.getId())
        {
            case R.id.btn_call_order:
            {
                showCallPopWin();
                break;
            }
            case R.id.btn_quotExcel:
            {
                showAllExcel();
                break;
            }
            case R.id.btn_see_singl:
            {
                if(!isSinglMode)
                {
                    updatePaperView(true);
                }
                break;
            }
            case R.id.btn_see_double:
            {
                if(isSinglMode)
                {
                    updatePaperView(false);
                }
                break;
            }
        }
    }
    
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,long id)
    {
        curPaperType.isChecked = false;
        curPaperType = (PaperType)quotTypeAdapter.getItem(position);
        curPaperType.isChecked = true;
        updatePaperView(true);
    } 
  
    private void initViews()
    {
        listView = getViewById(R.id.listView);
        quotTypeAdapter = new QuotTypeListAdapter(this);
        listView.setAdapter(quotTypeAdapter);
        listView.setDivider(getResources().getDrawable(R.drawable.transparent_bg));
        listView.setOnItemClickListener(this);
        ListView listView2 = getViewById(R.id.listView2);
        paperTablerAdapter = new PaperTableAdapter(this);
        listView2.setAdapter(paperTablerAdapter);
        
        btn_see_singl = getViewById(R.id.btn_see_singl);
        btn_see_double = getViewById(R.id.btn_see_double);
        
        btn_see_singl.setSelected(true);
        btn_see_double.setSelected(false);
    }
    
    private void load()
    {
        if(InitManager.getInstance().isInitOK())
        {
            if(InitManager.getInstance().isLogin())
            {
                // 已登录
                initOk();
            }else
            {
                // 未登录，重新加载地域
                loadInit();
            }
        }else
        {
            loadInit();
        }
    }
    
    // 载入地域信息
    private void loadInit()
    {
        bottom.setVisibility(View.GONE);
        mLoadingView.showLoadingView();
        // 获取初始化信息
        InitManager.getInstance().doInit(new NotifyListener<Boolean>()
        {
            @Override
            public void onSucceed(Boolean result)
            {
                runOnUiThread(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        initOk();
                    }
                });
            }
            
            @Override
            public void onError(final int resultCode)
            {
                runOnUiThread(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        mLoadingView.showLoadingErrView(HttpAction.getErrorMean(resultCode),false);
                    }
                });
            }
        });
    }
    
    private void updatePaperView(boolean singleable)
    {        
        if(curPaperType != null)
        {           
            if(singleable)
            {
                isSinglMode = true;
                btn_see_singl.setSelected(true);
                btn_see_double.setSelected(false);
                paperTablerAdapter.setList(curPaperType.paperList.get(0).priceList);                
            }else
            {
                isSinglMode = false;
                btn_see_singl.setSelected(false);
                btn_see_double.setSelected(true);
                paperTablerAdapter.setList(curPaperType.paperList.get(1).priceList);              
            }
        }
        if(curPaperType != null && curPaperType.paperList != null)
        {
            int size = curPaperType.paperList.size();
            btn_see_singl.setVisibility(size >= 1 ? View.VISIBLE : View.GONE);
            btn_see_double.setVisibility(size >= 2 ? View.VISIBLE : View.GONE);
            
            btn_see_singl.setText(size >= 1 ? curPaperType.paperList.get(0).name: "");
            btn_see_double.setText(size >= 2 ? curPaperType.paperList.get(1).name: "");
            
            if(size == 0 || (size >= 1 && TextUtils.isEmpty(curPaperType.paperList.get(0).name)))
            {
                // 没有类型
                getViewById(R.id.table_header).setVisibility(View.GONE);
            }else
            {
                getViewById(R.id.table_header).setVisibility(View.VISIBLE);
            }
        }
    }
    
    // 载入纸型列表
    private void load(String rid, int qid)
    {
        mLoadingView.showLoadingView();       
        QuotAction action  = new QuotAction();
        if(InitManager.getInstance().isLogin())
        {
            action.setCompanyNum(InitManager.getInstance().mLoginCompany.companyNum);
        }
        if(!TextUtils.isEmpty(rid))
        {
            action.setRid(rid+"");
        }
        action.setActionListener(new ActionListener<QuotInfo>()
        {
            @Override
            public void onSucceed(QuotInfo result)
            {
                if(result.isNoError())
                {
                    if(result.paperType != null && result.paperType.size() > 0)
                    {                      
                        curPaperType = result.paperType.get(0);                       
                        curPaperType.isChecked = true;                        
                        quotTypeAdapter.setList(result.paperType);
                        mLoadingView.showMainView();
                        updatePaperView(true);
                        bottom.setVisibility(View.VISIBLE);
                        showDirectPopWin();
                        // 获取备注
                        loadMark();
                        if(InitManager.getInstance().isLogin())
                        {
                            InitManager.getInstance().updateLastQutoDateTime(System.currentTimeMillis());
                        }
                    }else
                    {
                        mLoadingView.showLoadingErrView(R.string.tip_no_quot, false);
                    }
                }else
                {
                    mLoadingView.showLoadingErrView(result.resultInfo, false);
                }
            }
            @Override
            public void onError(int resultCode)
            {
                mLoadingView.showLoadingErrView(QuotAction.getErrorMean(resultCode), false);
            }
        });
        action.submit();
    }
    
    private void loadMark()
    {
        QuotMarkAction action = new QuotMarkAction();
        action.setActionListener(new ActionListener<QuotMark>()
        {
            @Override
            public void onSucceed(QuotMark result)
            {
                if(result.isNoError())
                {
                    markContnet = result.content;
                }else
                {
//                    showToast(result.resultInfo);
                }
            }
            @Override
            public void onError(int resultCode)
            {
                showToast(QuotMarkAction.getErrorMean(resultCode));
            }
        });
        action.submit();
    }
    
    // 查看完整的版本号
    private void showAllExcel()
    {
        QuotExcelAction action = new QuotExcelAction();
        if(InitManager.getInstance().isLogin())
        {
            action.setCompanyNum(InitManager.getInstance().mLoginCompany.companyNum);
        }
        Region   region =  (Region)spinner_area.getSelectedItem();
        if(region != null)
        {
            action.setRid(region.rid + "");
        }
        action.setActionListener(new ActionListener<ExcelHtml>()
        {
            @Override
            public void onSucceed(ExcelHtml result)
            {
                if(result.isNoError())
                {
                    FullQuotActivity.startActivity(NewPriceActivity.this, result.content);
                }else
                {
                    showToast("无完整报价表格！");
                }
            }

            @Override
            public void onError(int resultCode)
            {
                showToast(QuotExcelAction.getErrorMean(resultCode));
            }
        });
        action.submit();
    }
        
    private void showMarkPopWin()
    {
        if(markPopwin == null)
        {
            markPopwin = new MarkPopWindow(this);            
        }
        setPopWin(markPopwin);
        markPopwin.setContent(markContnet);
        getPopupWin().showAtLocation(getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);
    }
    
    private void showCallPopWin()
    {
        if(InitManager.getInstance().getOfferPhone() == null) return;
        if(callPopwin == null)
        {
            callPopwin = new CallPopWindow(this);
        }
        callPopwin.setPhoneText(InitManager.getInstance().getOfferPhone());
        callPopwin.setCallPhone(InitManager.getInstance().getOfferPhone());
        setPopWin(callPopwin);
        getPopupWin().showAtLocation(getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);
    }
    
    private void showDirectPopWin()
    {
        if(MyApplication.getContext().isDireactable())
        {
            setPopWin(new DirectPopWindow(this));
            getPopupWin().showAtLocation(getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);
        }
    }
       
    public static void startActivity(Context context)
    {
        Intent it = new Intent(context, NewPriceActivity.class);
        
        context.startActivity(it);
    } 
}
